<?php
error_reporting(E_ALL);
set_time_limit(0);
ob_implicit_flush();
?>
<html>
<head>
<style>
.errmsg{
	color:red;
}
</style>
</head>
<body>
<?php
if (isset($_POST["name"])){
	$mysqli = new mysqli('localhost', 'root', 'csci4140', '4140');

	if (!$mysqli) {
		printf("Connect failed: %s\n", mysqli_connect_error());
		exit();
	}
	
	if ($stmt = $mysqli->prepare("SELECT g.u_num FROM join_game g WHERE g.u_num=(SELECT MIN(u_num) FROM join_game g2 WHERE g2.joined=0)")) {

		/* bind parameters for markers */
		//$stmt->bind_param("s", $city);

		/* execute query */
		$stmt->execute();

		/* bind result variables */
		$stmt->bind_result($result);

		/* fetch value */
		if ($stmt->fetch()){
			$stmt->close();
			if ($stmt2 = $mysqli->prepare("SELECT g.u_num FROM join_game g WHERE g.joined>0 AND g.user=?")) {
				$stmt2->bind_param('s', $_POST["name"]);
				$stmt2->execute();
				if ($stmt2->fetch()!=NULL){
					echo "<div style=\"errmsg\">User name already exist</div>";
					header('Refresh: 2; url=login.php');
					exit();
				}
				$stmt2->close();
			}else{
				print("<div style=\"errmsg\">Error in SQL1</div>");
			}
				
			printf("Your id is %d\n", $result);
			$session = hash("md5", time()+$_POST["name"]);
			printf("Session: %s", $session);
			if ($stmt3 = $mysqli->prepare("UPDATE join_game g SET g.joined=1, g.timeout=FROM_UNIXTIME(?), g.user=?, g.session=? WHERE g.u_num=?")){
				$mysqldate = date( 'Y-m-d H:i:s');
				$phpdate = strtotime( $mysqldate );
				$stmt3->bind_param('sssi', $phpdate, $_POST["name"], $session, $result);
				$stmt3->execute();
				$stmt3->close();
				setcookie("login_session", $session, time()+30*60);
				header('Location: waitroom.php');
			}else{
				print("<div style=\"errmsg\">Error in SQL2</div>");
			}
		}else{
			$stmt->close();
			printf("Full.");
		}

		/* close statement */
	}

	$mysqli->close();
}
?>
Please input a username<br />
<form method="post">
<input type ="text" name="name" maxlength="30" /><br />
<input type ="Submit" value="submit" />
</form>
</body>
</html>